package aftersale

import (
	"context"
	"fmt"
	"mall/common/resultx"

	"mall/service/backend/common/i18n"
	"mall/service/order/rpc/internal/svc"
	"mall/service/order/rpc/types/order"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteAfterSaleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeleteAfterSaleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteAfterSaleLogic {
	return &DeleteAfterSaleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DeleteAfterSaleLogic) DeleteAfterSale(in *order.RemoveIDsReq) (*order.BaseResp, error) {
	logrus.Info(fmt.Sprintf("RemoveIDsReq: %+v", in))
	if len(in.Ids) == 0 {
		return nil, resultx.StatusError(resultx.AFTER_SALE_PARAM_INVALID, "")
	}
	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, err
	}

	var userId uint64
	if in.VisitorId != nil && *in.VisitorId > 0 {
		userId = *in.VisitorId
	}
	for _, id := range in.Ids {
		if id > 0 {
			err = l.svcCtx.AfterSaleRequest.SoftDelete(l.ctx, tx, id, userId)
			if err != nil {
				tx.Rollback()
				return nil, err
			}
		}
	}
	tx.Commit()

	return &order.BaseResp{
		Msg: i18n.DeleteSuccess,
	}, nil
}
